<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 17-4-12
 * Time: 16:05
 */

namespace frontend\widget;


use frontend\models\GoodsCategory;
use yii\base\Widget;
use yii\helpers\Url;

class BreadcrumbWidget extends Widget
{

    public $current_cate_id=1;

    public $current_cate;

    public $cateobj;

    public function run()
    {
        $this->getCategory();
        //当前分类
        $homeUrl = Url::home();
        $current_url = Url::to(['shop/list','goods_category_id'=>$this->current_cate_id]);
        $current_name= $this->current_cate->name;
        //查找父分类并且生成相应的代码
        $this->cateobj = $this->getParent($this->current_cate_id);
        $html = '';
        while(!empty($this->cateobj)){
            $html.= $this->generateBreadcrumb();
            $this->cateobj = $this->getParent($this->cateobj->id);
        }
        $html.='<a href="'.$current_url.'">'.$current_name.'</a>';
        $html = '<div class="breadcrumb"><h2>当前位置：<a href="'.$homeUrl.'">首页</a> > '.$html.'</h2></div>';
        /**
         *<div class="breadcrumb">
        <h2>当前位置：<a href="">首页</a> > <a href="">电脑、办公</a></h2>
        </div>
         */
        return $html;
    }

    public function getCategory(){
        $this->current_cate = GoodsCategory::findOne(['id'=>$this->current_cate_id]);
    }

    public function getParent($parent_id){
        //根据父id找到当前他的父分类 返回一个对象或者null
        return GoodsCategory::findOne(['parent_id'=>$parent_id]);
    }
    public function generateBreadcrumb(){
        $cateUrl = Url::to(['goods/list','goods_category_id'=>$this->cateobj->id]);
        $catename = $this->cateobj->name;
        $code = '<a href="'.$cateUrl.'">'.$catename.'</a> > ';
        return $code;
    }
}